<!--  -->
<template>
  <div class='authority'>
    <el-button type="primary" v-permissions="'company:add'" @click="addCompanyFun" style="margin-bottom: 10px;">新增</el-button>
    <el-form :inline="true" :model="formInUserCompany" class="demo-form-inline">
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="formInUserCompany.value1"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="模糊查询关键字">
        <el-input v-model="formInUserCompany.kw" placeholder="请输入关键字"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitSrearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table
        :data="getMyCompanyList"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          width="120">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址"
          width="260">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          >
          <template slot-scope="scope">
            <el-button v-permissions="'company:detail'" @click="getRoleDetail(scope.row.id,scope.row.roleName)" type="text" size="small">详情</el-button>
            <!-- <el-button @click="setRoleDetail(scope.row.id,scope.row.roleName)" type="text" size="small">修改</el-button> -->
            <el-button v-permissions="'company:delete'" @click="deletRoleUser(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-dialog
        title="用户详情"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :show-close="false"
        :close-on-press-escape="false"
        width="50%">
        <el-form
          ref="companyDetailUpdateRules"
          :rules="undatedDetailRules"
          :model="updatedCompany"
          :disabled="isDisabled"
          :inline="false"
          class="demo-form-inline"
          label-position="left"
          label-width="auto">
          <div class="filter-container">
            <el-form-item label="名称" prop="name">
              <el-input v-model="updatedCompany.name"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="updatedCompany.userName"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="updatedCompany.phone"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="detailsAddress">
              <el-cascader
                class="widthSmall"
                size="large"
                :options="options"
                v-model="updatedCompany.detailsAddress"
                @change="ChangeDetailsAddress">
              </el-cascader>
            </el-form-item>
            <el-form-item label="详细地址" prop="addressPlot">
              <el-input type="textarea" v-model="updatedCompany.addressPlot"></el-input>
            </el-form-item>
            <el-form-item label="过期时间" prop="expireTime">
              <el-date-picker type="date" placeholder="选择日期" v-model="updatedCompany.expireTime" style="width: 100%;" :default-value="parseTime(updatedCompany.createTime)"></el-date-picker>
            </el-form-item>
          </div>
        </el-form>
        <div class="buttons">
           <el-button type="primary" v-permissions="'company:update'" @click="setConfigUserRole" v-if="isDisabled">修改</el-button>
           <el-button type="primary" @click="submitConfigUser" v-if="!isDisabled">保存</el-button>
           <el-button @click="closeDiaDetail">关闭</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="新增公司"
        :visible.sync="addCompany"
        @close="closeDia"
        width="50%">
        <el-form ref="formName" :model="formAddCompany" :rules="addUserRule" label-width="80px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formAddCompany.name"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="formAddCompany.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="passWord">
            <el-input v-model="formAddCompany.passWord"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formAddCompany.phone"></el-input>
          </el-form-item>
          <el-form-item label="到期时间" prop="expireTime">
            <el-date-picker type="date" placeholder="选择日期" v-model="formAddCompany.expireTime" style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="地址" prop="selectedOptions">
            <el-cascader
              class="widthSmall"
              size="large"
              :options="options"
              v-model="formAddCompany.selectedOptions"
              @change="addressChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input type="textarea" v-model="formAddCompany.address"></el-input>
          </el-form-item>
        </el-form>
        <div style="width: 100%; text-align: center;">
          <el-button type="primary" @click="addMyNewCompany">保存</el-button>
        </div>
      </el-dialog>
    </div>
    <pagination
      class="pagination_container"
      :total="pagination.total"
      :page-sizes="[10, 20, 50, 100]"
      :page.sync="pagination.page"
      :limit.sync="pagination.pageSize"
      @pagination="getCompanyListInit"
    />
  </div>
</template>

<script>
import { provinceAndCityData, CodeToText } from 'element-china-area-data'
import { companyAdd, companyList, companyDetail, companyDelete, companyUpdate } from '@/api/Company'

import { parseTime } from '@/until/paramRou'
import Pagination from '@/components/pagination'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    Pagination
  },
  data () {
    // 这里存放数据
    return {
      options: provinceAndCityData, // 省市区数据
      isDisabled: true,
      updatedCompany: { // 修改公司
        address: '',
        cityCode: '',
        companyId: '',
        expireTime: '',
        name: '',
        phone: '',
        userId: '',
        userName: '',
        detailsAddress: [],
        wordForDetailAddress: '',
        addressPlot: ''
      },
      undatedDetailRules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入您的手机号' },
          {
            validator (_, value, callback) {
              const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
              if (!regTel.test(value)) {
                callback(new Error('手机号不符合规则'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        detailsAddress: [
          { required: true, trigger: 'change', message: '请选择地址' }
        ],
        expireTime: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ],
        userName: [
          { required: true, trigger: 'blur', message: '请输入您的用户名' }
        ],
        addressPlot: [
          { required: true, trigger: 'blur', message: '请输入您的详细地址' }
        ]
      },
      getMyCompanyList: [], // 公司列表
      formAddCompany: {
        name: '',
        passWord: '',
        phone: '',
        selectedOptions: [],
        address: '',
        cityProvince: '',
        cityCode: '',
        expireTime: '',
        userName: ''
      },
      // 新增 rule 验证
      addUserRule: {
        name: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        passWord: [
          { required: true, trigger: 'blur', message: '请输入您的密码' },
          { min: 6, max: 12, message: '长度为6-12位', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入您的手机号' },
          {
            validator (_, value, callback) {
              const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
              if (!regTel.test(value)) {
                callback(new Error('手机号不符合规则'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        selectedOptions: [
          { required: true, trigger: 'change', message: '请选择地址' }
        ],
        expireTime: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ],
        userName: [
          { required: true, trigger: 'blur', message: '请输入您的用户名' }
        ],
        address: [
          { required: true, trigger: 'blur', message: '请输入您的详细地址' }
        ]
      },
      // 分页
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      // 查询
      formInUserCompany: {
        value1: [],
        kw: '',
        isExpire: '',
        status: ''
      },
      // checked: false,
      dialogVisible: false,
      userNameGet: '',
      userRoleIdGet: null,
      userRemarkGet: '',
      userList: JSON.parse(sessionStorage.getItem('routerList')),
      defaultCheckRole: [],
      setRoleIdArrFir: [],
      setRoleIdArrSen: [],
      addCompany: false,
      form: {
        roleName: '',
        remark: ''
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 修改详情地址
    ChangeDetailsAddress (arr) {
      this.updatedCompany.detailsAddress = [arr[0], arr[1]]
      this.updatedCompany.wordForDetailAddress = CodeToText[arr[0]] + CodeToText[arr[1]]
    },
    // 地址选择 - 新增
    addressChange (arr) {
      this.formAddCompany.cityCode = arr[0] + '-' + arr[1]
      this.formAddCompany.cityProvince = CodeToText[arr[0]] + CodeToText[arr[1]]
    },
    // 获取用户列表
    getCompanyListInit () {
      if (
        this.formInUserCompany.value1 === null ||
        this.formInUserCompany.value1[1] === undefined ||
        this.formInUserCompany.value1[0] === undefined) {
        companyList({
          endTime: '',
          startTime: '',
          kw: this.formInUserCompany.kw,
          limit: this.pagination.pageSize,
          page: this.pagination.page
        }).then(res => {
          if (res.code === '200') {
            this.getMyCompanyList = res.data.records
            if (res.data.total > 0 && Math.ceil(res.data.total / this.pagination.size) < this.pagination.page) {
              this.pagination.page = Math.ceil(res.data.total / this.pagination.size)
              this.getCompanyListInit()
            } else {
              this.pagination.total = res.data.total
            }
          } else {
            this.$message({
              message: res.message,
              type: 'warning'
            })
          }
        })
      } else {
        companyList({
          endTime: parseTime(this.formInUserCompany.value1[1]),
          startTime: parseTime(this.formInUserCompany.value1[0]),
          kw: this.formInUserCompany.kw,
          limit: this.pagination.pageSize,
          page: this.pagination.page
        }).then(res => {
          if (res.code === '200') {
            this.getMyCompanyList = res.data.records
            if (res.data.total > 0 && Math.ceil(res.data.total / this.pagination.size) < this.pagination.page) {
              this.pagination.page = Math.ceil(res.data.total / this.pagination.size)
              this.getCompanyListInit()
            } else {
              this.pagination.total = res.data.total
            }
          } else {
            this.$message({
              message: res.message,
              type: 'warning'
            })
          }
        })
      }
    },
    // 打开新增弹框
    addCompanyFun () {
      this.addCompany = true
    },
    // 新增保存
    addMyNewCompany () {
      this.$refs.formName.validate((valid) => {
        if (valid) {
          this.formAddCompany.expireTime = new Date(this.formAddCompany.expireTime).getTime()
          const companyObj = {
            address: this.formAddCompany.cityProvince + '-' + this.formAddCompany.address,
            cityCode: this.formAddCompany.cityCode,
            expireTime: this.formAddCompany.expireTime,
            name: this.formAddCompany.name,
            passWord: this.formAddCompany.passWord,
            phone: this.formAddCompany.phone,
            userName: this.formAddCompany.userName
          }
          companyAdd(companyObj).then(res => {
            this.addCompany = false
            if (res.code === '200') {
              this.getCompanyListInit()
              this.$message({
                message: '操作成功',
                type: 'success'
              })
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 查询
    submitSrearch () {
      this.getCompanyListInit()
    },
    // 重置
    resetForm () {
      this.formInUserCompany.value1 = []
      this.formInUserCompany.kw = ''
      this.formInUserCompany.isExpire = ''
      this.formInUserCompany.status = ''
    },
    // 删除用户
    deletRoleUser (val) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        companyDelete(val).then(res => {
          if (res.code === '200') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getCompanyListInit()
          } else {
            this.$message({
              type: 'info',
              message: res
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 用户详情
    getRoleDetail (val, name) {
      this.userNameGet = name
      this.userRoleIdGet = val
      companyDetail(val).then(res => {
        this.updatedCompany = res.data
        this.updatedCompany.companyId = res.data.id
        console.log(this.updatedCompany)
        const start = this.updatedCompany.address.indexOf('-') + 1
        const detailEnd = this.updatedCompany.address.length
        const cityEnd = this.updatedCompany.cityCode.length
        const tagNum = this.updatedCompany.cityCode.indexOf('-')
        const provinceCode = this.updatedCompany.cityCode.substring(0, tagNum)
        const cityForCode = this.updatedCompany.cityCode.substring(tagNum + 1, cityEnd)
        this.updatedCompany.detailsAddress = [provinceCode, cityForCode]
        this.updatedCompany.wordForDetailAddress = CodeToText[provinceCode] + CodeToText[cityForCode]
        this.updatedCompany.addressPlot = this.updatedCompany.address.substring(start, detailEnd)

        this.dialogVisible = true
      })
    },
    // 修改用户详情
    setConfigUserRole () {
      this.$confirm('是否确认修改公司信息', '提示', {
        confirmButtonText: '确定',
        showCancelButton: '取消',
        distinguishCancelAndClose: false
      }).then(() => {
        this.isDisabled = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消!'
        })
      })
    },
    // 保存修改后用户信息
    submitConfigUser () {
      this.$refs.companyDetailUpdateRules.validate((valid) => {
        if (valid) {
          const resAddress = this.updatedCompany.addressPlot === undefined ? '' : this.updatedCompany.addressPlot
          const role = {
            cityCode: this.updatedCompany.detailsAddress[0] + '-' + this.updatedCompany.detailsAddress[1],
            companyId: this.updatedCompany.companyId,
            expireTime: new Date(this.updatedCompany.expireTime).getTime(),
            name: this.updatedCompany.name,
            phone: this.updatedCompany.phone,
            userId: this.updatedCompany.userId,
            userName: this.updatedCompany.userName,
            address: this.updatedCompany.wordForDetailAddress + '-' + resAddress
          }
          companyUpdate(role).then(res => {
            if (res.code === '200') {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.isDisabled = true
              this.getCompanyListInit()
            } else {
              this.$message({
                type: 'info',
                message: res.message
              })
            }
          })
        }
      })
    },
    // 关闭新增弹框
    closeDia () {
      this.formAddCompany = {}
    },
    // 关闭详情弹框
    closeDiaDetail () {
      this.dialogVisible = false
      this.isDisabled = true
    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getCompanyListInit()
  }
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
.authority {
  width: 100%;
  height: 100%;
}
.fir {
  width: auto;
  height: 30px;
  line-height: 30px;
  span {
    margin-left: 10px;
    padding: 5px;
    width: 30%;
  }
}
.sen {
  margin: 5px auto;
  width: 80%;
  padding: 10px;
  border: 1px solid #f0f0f0;
}
.buttons {
  width: 100%;
  text-align: center;
}
</style>
